package com.example.exjnidemo.exbluetooth01.u;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.Switch;

import com.example.exjnidemo.exbluetooth01.i.CallBack;
import com.example.exjnidemo.exbluetooth01.socketclient.ClientBluetoothSocketUtil;
import com.example.exjnidemo.exbluetooth01.a.FindBluetoothAdapter;
import com.example.exjnidemo.exbluetooth01.LogUtil;
import com.example.exjnidemo.exbluetooth01.R;
import com.example.exjnidemo.exbluetooth01.m.YXJBluetoothManager;
import com.example.exjnidemo.exbluetooth01.i.ScanBluetoothListener;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class MainActivity extends AppCompatActivity{

    private Switch mSwitch ;
    private RecyclerView mRecyclerView ;
    private FindBluetoothAdapter adapter ;
    private ProgressBar mProgressBar ;
    private Button btn_scan ;
    private List<BluetoothDevice> list = new ArrayList<>() ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        YXJBluetoothManager.getInstance().setScanBluetoothListener(scanBluetoothListener);
        initView();
    }

    private void initView() {
        setContentView(R.layout.activity_main);
        mSwitch = findViewById(R.id.mSwitch) ;
        mProgressBar = findViewById(R.id.mProgressBar);
        btn_scan = findViewById(R.id.btn_scan) ;

        initRecyclerView();
        initSwitch();
    }



    private void initSwitch() {
        mSwitch.setChecked(YXJBluetoothManager.getInstance().isBlueEnable());
        mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    if (YXJBluetoothManager.getInstance().openBluetooth()){
                        mRecyclerView.setVisibility(View.VISIBLE);
                    }
                }else {
                    YXJBluetoothManager.getInstance().closeBluetooth();
                    mRecyclerView.setVisibility(View.GONE);
                    mProgressBar.setVisibility(View.GONE);
                    btn_scan.setVisibility(View.VISIBLE);
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
            }
        });
    }


    private void initRecyclerView() {
        mRecyclerView = findViewById(R.id.mRecyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL);
        GradientDrawable gradientDrawable =new GradientDrawable() ;
        gradientDrawable.setColors(new int[]{
                Color.BLUE , Color.RED
        });
        gradientDrawable.setOrientation(GradientDrawable.Orientation.LEFT_RIGHT);
        gradientDrawable.setSize(0,2);
        dividerItemDecoration.setDrawable(gradientDrawable);
        mRecyclerView.addItemDecoration(dividerItemDecoration);
        mRecyclerView.setAdapter(adapter = new FindBluetoothAdapter(list,this));
        adapter.setOnItemClickListener(new FindBluetoothAdapter.OnItemClickListener() {
            @Override
            public void onClick(final BluetoothDevice device) {
                showFindBluetooth(device);
                new XPopup.Builder(MainActivity.this)
                        .asBottomList("",new String[]{"开始配对","取消配对","解除配对","发送信息"}, new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                switch (position){
                                    case 0:
                                        YXJBluetoothManager.getInstance().createBond(device);
                                        break;
                                    case 1:
                                        YXJBluetoothManager.getInstance().cancelBondProcess(device.getClass(),device);
                                        break;
                                    case 2:
                                        YXJBluetoothManager.getInstance().removeBond(device);
                                        break;
                                    case 3:
                                        try {
                                            sendMsg(device);
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                        break;
                                }
                            }
                        }).show();
            }
        });
    }




    /**
     * 配对的蓝牙发送信息
     *
     * @param device
     */
    private void sendMsg(BluetoothDevice device) throws IOException {
        if (device.getBondState() == BluetoothDevice.BOND_BONDED){
            ClientBluetoothSocketUtil clientBluetoothSocketUtil = new ClientBluetoothSocketUtil(device);
            clientBluetoothSocketUtil.startConnect(new CallBack() {
                @Override
                public void onResult(Object o) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtil.t(MainActivity.this, (String) o);
                        }
                    });
                }

                @Override
                public void onError(int code, String msg) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtil.t(MainActivity.this,msg);
                        }
                    });
                }
            });
        }else {
            LogUtil.t(MainActivity.this,"您还未配对连接！");
        }
    }


    /**
     * 开始扫描蓝牙
     *
     * @param view
     */
    public void scanBluetooth(View view) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                        MainActivity.this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        10);
            }else {
                if (!YXJBluetoothManager.getInstance().startDiscovery()){
                    LogUtil.t(this,"开启扫描失败！");
                }
            }
        }else {
            if (!YXJBluetoothManager.getInstance().startDiscovery()){
                LogUtil.t(this,"开启扫描失败！");
            }
        }
    }


    /**
     * 自动扫描
     */
    public void autoStart(){


    }





    /**
     * 打印找到的蓝牙设备
     *
     * @param device
     */
    private void showFindBluetooth(BluetoothDevice device) {
        HashMap<String,Object> map= new HashMap<>() ;
        map.put("Name",device.getName());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            map.put("Type",device.getType());
        }
        map.put("Uuids",device.getUuids());
        map.put("BondState",device.getBondState());
        map.put("Address",device.getAddress());
        LogUtil.v("scanResult  device = "+new Gson().toJson(map));
    }




    /**
     * 判断新增的是否与已存在重复
     *
     * 如果存在删除  将最新放在第一个
     *
     * @param device
     * @return
     */
    private boolean isContain(BluetoothDevice device) {
        boolean b = false ;
        Iterator<BluetoothDevice> it = list.iterator();
        while (it.hasNext()){
            BluetoothDevice d=it.next() ;
            if (d.getAddress().equals(device.getAddress())) {
                it.remove();
                b = true;
                break;
            }
        }

        if (b){
            list.add(0,device);
            adapter.notifyDataSetChanged();
        }
        return b ;
    }




    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 10 :
                if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    /*同意了*/
                    if (!YXJBluetoothManager.getInstance().startDiscovery()){
                        LogUtil.t(this,"开启扫描失败！");
                    }
                }else {

                }
                break;
        }
    }

    private ScanBluetoothListener scanBluetoothListener = new ScanBluetoothListener(){

        @Override
        public void startScan() {
            mProgressBar.setVisibility(View.VISIBLE);
            btn_scan.setVisibility(View.GONE);
        }


        @Override
        public void finishedScan() {
            mProgressBar.setVisibility(View.GONE);
            btn_scan.setVisibility(View.VISIBLE);
        }


        @Override
        public void scanResult(BluetoothDevice device) {
            if (!TextUtils.isEmpty(device.getName())){
                showFindBluetooth(device);
                if (!isContain(device)){
                    list.add(device) ;
                    adapter.notifyDataSetChanged();
                }
            }
        }

        @Override
        public void onConfirmationBond(BluetoothDevice device, boolean isConfirmation) {
            if (isContain(device)){
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onBonding(BluetoothDevice device) {
            if (isContain(device)){
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onBonded(BluetoothDevice device) {
            if (isContain(device)){
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onBondNone(BluetoothDevice device) {
            if (isContain(device)){
                adapter.notifyDataSetChanged();
            }
        }
    };




    @Override
    protected void onResume() {
        super.onResume();
        YXJBluetoothManager.getInstance().register(this);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        YXJBluetoothManager.getInstance().unregister(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mProgressBar.setVisibility(View.GONE);
        btn_scan.setVisibility(View.VISIBLE);
        YXJBluetoothManager.getInstance().cancelDiscovery();
    }
}